$(document).ready(function(){
	$("#personName").keydown(function(evt){
		autoCorrect('personName', evt);
	});
	$("#adrStreet").keydown(function(evt){
		autoCorrect('adrStreet', evt);
	});
	$("#patient_relative_name").keydown(function(evt){
		autoCorrect('patient_relative_name', evt);
	});
	$("#patient_relative_address").keydown(function(evt){
		autoCorrect('patient_relative_address', evt);
	});
	setAutoComplete2("ward_name", "../Patient/getWardFromDistrictAjax?set_ajax_view&part=","district_id","district_id");
	setAutoComplete("registeredHospital","../Patient/getHospitalSuggestionAjax?set_ajax_view&part=");

	if ($.trim($("input#insuranceCode").val()).length == 0 ) {
		$('input#insurance_date_issued').val('');
    		$('input#insurance_date_issued').attr('readonly', 'readonly');
			$('input#insurance_date_issued').css('border-color', '#DDD');
			$('input#issued_mm').val('');
    		$('input#issued_mm').attr('readonly', 'readonly');
			$('input#issued_mm').css('border-color', '#DDD');
			$('input#issued_dd').val('');
    		$('input#issued_dd').attr('readonly', 'readonly');
			$('input#issued_dd').css('border-color', '#DDD');
			
			$('input#insurance_date_expired').val('');
	    	$('input#insurance_date_expired').attr('readonly', 'readonly');
	    	$('input#insurance_date_expired').css('border-color', '#DDD');
	    	$('input#expired_mm').val('');
    		$('input#expired_mm').attr('readonly', 'readonly');
			$('input#expired_mm').css('border-color', '#DDD');
			$('input#expired_dd').val('');
    		$('input#expired_dd').attr('readonly', 'readonly');
			$('input#expired_dd').css('border-color', '#DDD');			
    	
    		$('select#insurance_type').attr('disabled', 'disabled');
    		
    		$('#registeredHospital').attr('readonly', 'readonly').css('border-color', '#DDD');
    }
  
	$('select#province_id').change( function() {
		provinceChange('province_id', 'district_id', 'ward_name');		
	});
	
	$('select#workingProvince').change(function(){
		provinceChange('workingProvince', 'workingDistrict', '');		
	});
	
	$('select#district_id').change(function(){
		districtChange('district_id', 'ward_name');
	});

    $('input#personName').blur(function() {
    	isNotEmpty($(this), _("Empty name"), 'statusMessage');
    });
    $('input#birthday').blur(function() {
    	checkBirthday($(this),$('#DOB_mm'),$('#DOB_dd'));
    });
    $('input#DOB_mm').blur(function(){
    	checkMonth($(this),false,'','statusMessage');
    });
    $('input#DOB_dd').blur(function(){
    	checkDay($(this),false,'','statusMessage');
    });
    $('input#person_age').change(function() {    	
    	checkAge($(this));
    });
    $('input#insuranceCode').bind("click keydown blur", function() {
    	if ($.trim($(this).val()).length > 0 ) {
    		$('input#insurance_date_issued').removeAttr('readonly');
    		$('input#insurance_date_issued').css("border-color", "#AAA");
    		$('input#issued_mm').removeAttr('readonly');
    		$('input#issued_mm').css("border-color", "#AAA");
    		$('input#issued_dd').removeAttr('readonly');
    		$('input#issued_dd').css("border-color", "#AAA");
    		
    		$('input#insurance_date_expired').removeAttr('readonly');
    		$('input#insurance_date_expired').css("border-color", "#AAA");
    		$('input#expired_mm').removeAttr('readonly');
    		$('input#expired_mm').css("border-color", "#AAA");
    		$('input#expired_dd').removeAttr('readonly');
    		$('input#expired_dd').css("border-color", "#AAA");
    		
    		$('select#insurance_type').removeAttr('disabled');
    		
    		$('#registeredHospital').removeAttr('readonly').css("border-color", "#AAA");	
    	} else {
    		$('input#insurance_date_issued').val('');
    		$('input#insurance_date_issued').attr('readonly', 'readonly');
			$('input#insurance_date_issued').css('border-color', '#DDD');
			$('input#issued_mm').val('');
    		$('input#issued_mm').attr('readonly', 'readonly');
			$('input#issued_mm').css('border-color', '#DDD');
			$('input#issued_dd').val('');
    		$('input#issued_dd').attr('readonly', 'readonly');
			$('input#issued_dd').css('border-color', '#DDD');
			
			$('input#insurance_date_expired').val('');
	    	$('input#insurance_date_expired').attr('readonly', 'readonly');
	    	$('input#insurance_date_expired').css('border-color', '#DDD');
	    	$('input#expired_mm').val('');
    		$('input#expired_mm').attr('readonly', 'readonly');
			$('input#expired_mm').css('border-color', '#DDD');
			$('input#expired_dd').val('');
    		$('input#expired_dd').attr('readonly', 'readonly');
			$('input#expired_dd').css('border-color', '#DDD');
			
	    	$('select#insurance_type').attr('disabled', 'disabled');
	    	
	    	$('#registeredHospital').val('').attr('readonly', 'readonly').css('border-color', '#DDD');
    	}
    });
    $('input#insurance_date_issued').blur(function() {
    	checkInsuranceIssueDate($(this), $('#issued_mm'), $('#issued_dd'));
    });
    $('input#insurance_date_expired').blur(function() {
    	checkInsuranceExpireDate($(this),$('#expired_mm'), $('#expired_dd'));
    });
      
    $('input#insuranceCode').blur(function() {
    	checkInsuranceCode($(this));
    });
    $('input#person_email').blur(function() {
    	checkEmail($(this), _("Invalid email"), 'statusMessage', '#AAA');
    });
    $('input#genderMale').blur(function() {
    	checkSelectGender();
    });
    $('input#genderFemale').blur(function() {
    	checkSelectGender();
    });
    
    $('input#person_phone_number').blur(function(){
    	checkNumber($(this), _("Invalid phone number"), 'statusMessage', '#AAA');
    });
    $('input#patient_relative_number').blur(function(){
    	checkNumber($(this), _("Invalid phone number"), 'statusMessage', '#AAA');
    });
});

function provinceChange(provinceId, districtId, wardId) {
	$.ajax ({
		type:    "GET",
		url:	  "../Patient/getDistrictFromProvinceAjax?set_ajax_view",
		data:	  "provice_id=" + $('#' + provinceId).val(),
		dataType: "json",
		success:	function(data) {
			if(data.districtList.length > 0){
				$('#' + districtId).html(data.districtList);
			}else{
				var option = "<option value='0' label='- " + _('District') + " -'>- " + _('District') + " -</option>";
				$('#' + districtId).html(option);
			}
			if(wardId != null && wardId != ''){
				districtChange(districtId, wardId);
			}
		}
	});
}

function districtChange(districtId, wardId){
	$.ajax ({
		type:    "GET",
		url:	  "../Patient/ListWardFromDistrictAjax?set_ajax_view",
		data:	  "district_id=" + $('#' + districtId).val(),
		dataType: "json",
		success:	function(data) {
			if(data.wardList.length > 0){
				$('#' + wardId).html(data.wardList);
			}else{
				var option = "<option value='0' label='- " + _('Ward') + " -'>- " + _('Ward') + " -</option>";
				$('#' + wardId).html(option);
			}
		}
	});
}

function checkBirthday(objYear, objMonth, objDay) {
   		var res 	= 	checkDate(objYear, objMonth, objDay, true, _('Empty date of birth'), 'statusMessage', true);
   		if(!res){
   			return false;
   		}
   		$('input#person_age').css("border-color", "#AAA");
   		getAge('birthday','person_age');
   		return true;   	
}

function checkAge(obj) {
	if (obj.val().length > 0 && !obj.val().match(/^[0-9]+$/)) {
   		obj.css("border-color", "red");
   		obj.focus();
		$('span#statusMessage').text(_("Invalid age")).show();
   	} else if (obj.val().length > 0) {
   		obj.css("border-color", "#AAA");
   		$('input#birthday').css("border-color", "#AAA");
   		$('input#DOB_mm').css("border-color", "#AAA");
   		$('input#DOB_dd').css("border-color", "#AAA");
   		$('span#statusMessage').text('');
   		getBirthday('person_age','birthday');
   	} else {
   		obj.css("border-color", "#AAA");
   		$('span#statusMessage').hide();
   	}
}

function checkInsuranceIssueDate(objYear, objMonth, objDay) {
	if ($.trim($('input#insuranceCode').val()).length > 0) {
		return checkFullDate(objYear, objMonth, objDay, true,  _('Empty issue date'), 'statusMessage', true);
	}
	return true;
}

function checkInsuranceExpireDate(objYear, objMonth, objDay) {
	if ($.trim($('input#insuranceCode').val()).length > 0) {
		var res = checkFullDate(objYear, objMonth, objDay, true, _('Empty expiry date'), 'statusMessage', false);
		if (res == false) {
			return false;
		} 
		var expiredDate	=	$.trim(objDay.val()) + "/" + $.trim(objMonth.val()) + "/" + $.trim(objYear.val());
		var result = compareDate(expiredDate, "today");
		if (result == "ltToday") {
			objYear.css("border-color", "red");
			objMonth.css("border-color", "red");
			objDay.css("border-color", "red");
  			$('span#statusMessage').text(_('Expiry date is less than current date')).show();
			return false;
		}
	}
	if(!objYear.attr('readonly')){
		objYear.css("border-color", "#AAA");
		objMonth.css("border-color", "#AAA");
		objDay.css("border-color", "#AAA");
	}
  	$('span#statusMessage').text('').hide();
	return true;
}

function savePatient() {
	var submitData = $('#editDemographicsForm').formSerialize();
	
	$.ajax ({
		type:    "GET",
		url:	 "../Patient/editDemographicsAjax?set_ajax_view",
		data:	 submitData,
		dataType: "json",
		beforeSend: function() {			
			$('#pageContent').hide();
			$("#barLoading").show();
		},
		complete: function() {
			
		},
		success: function(data) {
			if(data.personSaved){
				$('span#patientName').text(data.patientName);
				$('span#patientDob').text(data.patientDob);
			};
			$.ajax ({
				type: 	  "GET",
				data:     "patientId=" + $('input#person_id').val(), 
				url:	  "../Patient/loadDemographicsPage?set_ajax_view",
				dataType: "html",
				success:  function(data) {
					$("#barLoading").hide();
					$("#pageContent").html(data).show();
					update_data();
				}
			});
		}
	});
}

function checkInsuranceType(obj) {
	if ($.trim($('input#insuranceCode').val()).length > 0) {		
		if (!(obj.val() == 'required' || obj.val() == 'volunteered')) {
			obj.css("border-color", "red");
			$('span#statusMessage').text(_("Not yet select insurance type")).show();
  			return false;
		}
	}
	obj.css("border-color", "#AAA");
	$('span#statusMessage').text("").hide();
	return true;
}

function checkInsuranceCode(obj) {
	var code = obj.val();
	if ($.trim(code).length > 0) {
		if (!code.match(/^[0-9A-Za-z]+$/)) {
			obj.css("border-color", "red");
			$('span#statusMessage').text(_("Invalid insurance number. Only accept alphanumberic characters")).show();
  			return false;
		} else {			
  			obj.css("border-color", "#AAA");
			$('span#statusMessage').text("").hide();
			return true;
		}
	}
	return true;
}

function isReadyToSubmit() {
	if (!isNotEmpty($('input#personName'), _('Empty name'), 'statusMessage')) {
		return false;
	}
	if (!checkSelectGender()) {
		return false;
	}
	if (!checkBirthday($('input#birthday'),$('input#DOB_mm'), $('input#DOB_dd'))) {
		return false;
	}
	
	if (!checkEmail($('input#person_email'), _("Invalid email"), 'statusMessage', '#AAA')) {
		return false;
	}	
	if (!checkInsuranceCode($('input#insuranceCode'))) {
		return false;
	}
	if (!checkInsuranceType($('select#insurance_type'))) {
		return false;
	}
	if (!checkInsuranceIssueDate($('#insurance_date_issued'), $('#issued_mm'), $('#issued_dd'))) {
		return false;
	}
	if (!checkInsuranceExpireDate($('#insurance_date_expired'),$('#expired_mm'), $('#expired_dd'))) {
		return false;
	}
	if(!checkNumber($('input#person_phone_number'), _("Invalid phone number"), 'statusMessage', '#AAA')){
		return false;
	}
	if($('input#patient_relative_number').val() != '' && !(checkNumber($('input#patient_relative_number'), _("Invalid phone number"), 'statusMessage', '#AAA'))){
		return false;
	}
		
	return true;
}

function isReadyToSubmitAdd() {
	var res = isReadyToSubmit();
	if (res) {
		$('div#barLoading').show('fast');
		$('div#addDemographics').hide('fast');
	} 
	return res;
}

function checkSelectGender() {
	if ($('#genderMale').is(':checked') || $('#genderFemale').is(':checked')) {
		$('span#statusMessage').text("").hide();
		return true;
	}
	$('span#statusMessage').text(_("Not yet select gender")).show();
  	return false;
}
// this function is used to update data in PatientNumberToAddress Report after savePatient is finished. 
function update_data(){
	if($('select#province_id').val() == ''){
		$('#province_' + $('input#person_id').val() + '_name_span').html('');
		$('#province_' + $('input#person_id').val() + '_name_span').show();
	}else{	
		$('#province_' + $('input#person_id').val() + '_name_span').html($('select#province_id :selected').text());
		$('#province_' + $('input#person_id').val() + '_name_span').show();
	} 			
	if($('select#district_id').val() == ''){
		$('#district_' + $('input#person_id').val() + '_name_span').html('');
		$('#district_' + $('input#person_id').val() + '_name_span').show();
	}else{	
		$('#district_' + $('input#person_id').val() + '_name_span').html($('select#district_id :selected').text());
		$('#district_' + $('input#person_id').val() + '_name_span').show();
	}
	if($('select#nationality').val() == 'empty'){
		$('#country_' + $('input#person_id').val() + '_name_span').html('');
		$('#country_' + $('input#person_id').val() + '_name_span').show();
	}else{
		$('#country_' + $('input#person_id').val() + '_name_span').html($('select#nationality :selected').text());
		$('#country_' + $('input#person_id').val() + '_name_span').show();
	}
	$('#street_' + $('input#person_id').val() + '_name_span').html($('input#street').val());
	$('#street_' + $('input#person_id').val() + '_name_span').show();
	$('#birth_day_' + $('input#person_id').val()).html($('span#birth_day').text());
 	$('#birth_day_' + $('input#person_id').val()).show();
 	$('#age_' + $('input#person_id').val()).html($('span#age').text());
 	$('#age_' + $('input#person_id').val()).show();
}

// autoTab
function autoTab(thisElem, maxLength, nextElem){
	if(thisElem.value.length == maxLength){
		thisElem.blur();
		$('#' + nextElem).focus();
	}
}
